<template>
  <div>
    <div>
      <el-form :inline="true" :model="selectFile" ref="selectFile" class="demo-form-inline">
        <el-row :gutter="5">
          <el-col :span="6">
            <el-form-item prop="typeName" label="文件名称:" style="width:100%" label-width="90px">
              <el-input v-model="selectFile.fileName" placeholder="文件名称" size="medium"
                        autocomplete="off" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="createDate" label="创建时间:" style="width:100%" label-width="90px">
              <el-date-picker
                  v-model="selectFile.createDate"
                  type="daterange"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :default-time="['00:00:00', '23:59:59']" style="width:215px" size="medium" autocomplete="off"
                  clearable>
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: right">
            <el-form-item>
              <el-button type="primary" @click="onSubmit('selectFile')" size="medium">查询</el-button>
              <el-button @click="resetForm('selectFile')" size="medium">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div>
      <el-card style="width: 100%;  height: calc(100vh - 330px);">
        <el-row>
          <el-col :span="22">
            <el-popover
                placement="right"
                width="200"
                trigger="click" v-model="showPopover" @hide="handleHide">
              <el-form :model="showCol" status-icon ref="columnValues" class="demo-ruleForm">
                <el-form-item>
                  <el-checkbox-group v-model="columnValues" @change="handleCheckedCitiesChange">
                    <el-row :gutter="20">
                      <el-col :span="12" v-for="col in columns">
                        <el-checkbox :label="col" :key="col">{{ col }}</el-checkbox>
                      </el-col>
                    </el-row>
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item style="text-align: right">
                  <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange"
                               style="margin-right: 20px">全选
                  </el-checkbox>
                  <el-button type="primary" @click="submitFormShowCol('showCol')" size="mini">应用</el-button>
                  <el-button @click="resetFormShowCol('showCol')" size="mini">重置</el-button>
                </el-form-item>
              </el-form>
              <el-button slot="reference" type="primary" plain size="small" icon="el-icon-s-tools">自定义列</el-button>
            </el-popover>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" icon="el-icon-upload" size="small" @click="uploadFile">上传附件</el-button>
          </el-col>
        </el-row>
        <template>
          <el-table :data="tableData" max-height="300" v-loading="loading" element-loading-text="拼命加载中"
                    element-loading-spinner="el-icon-loading">
            <template slot="empty">
              <el-empty :image-size="100" description='暂无数据'></el-empty>
            </template>
            <el-table-column fixed prop="id" label="编号" sortable></el-table-column>
            <el-table-column fixed label="文件类型" v-if="showCol.includes('文件类型')"  width="100">
              <template slot-scope="scope">
                <i :class="getFileIconClass(scope.row.url)"></i>
                {{ getFileType(scope.row.url) }}
              </template>
            </el-table-column>
            <el-table-column prop="fileName" v-if="showCol.includes('文件名称')" label="文件名称"
                             width="400" sortable></el-table-column>
            <el-table-column v-if="showCol.includes('文件访问路径')" label="文件访问路径"
                             width="650" sortable>
              <template slot-scope="scope">
                <a :href="scope.row.url" target="_blank">{{ scope.row.url }}</a>
              </template>
            </el-table-column>
            <el-table-column prop="createBy" v-if="showCol.includes('创建人')" label="创建人" width="150"></el-table-column>
            <el-table-column prop="createDate" v-if="showCol.includes('创建时间')" label="创建时间" width="180"
                             sortable></el-table-column>
            <el-table-column prop="lastUpdateBy" v-if="showCol.includes('修改人')" label="修改人"
                             width="150"></el-table-column>
            <el-table-column prop="lastUpdateDate" v-if="showCol.includes('修改时间')" label="修改时间" width="180"
                             sortable></el-table-column>
            <el-table-column fixed="right" label="操作" width="120">
              <template slot-scope="scope">
                <el-button
                    @click="updown(scope.$index, scope.row)"
                    type="text"
                    size="small">
                  下载
                </el-button>
                <el-button
                    @click="deleteRow(scope.$index, scope.row)"
                    type="text"
                    size="small" style="color:red;">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <div class="block" style="margin-top: 15px;text-align: right">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10,20, 50, 100, 200,500]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total" background small>
          </el-pagination>
        </div>
      </el-card>
    </div>
    <el-drawer
        title="上传附件"
        :visible.sync="drawer"
        :direction="direction"
        :before-close="handleClose">
      <el-upload
          class="upload-demo"
          drag
          :before-upload="beforeUpload"
          :multiple="false" style="text-align: center" :show-file-list = "true">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
    </el-drawer>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectFile: {
        fileName: "",
        createDate: []
      },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 10,
      loading: false,
      showCol: ['文件名称', '文件类型', '文件访问路径', '创建人', '创建时间', '修改人', '修改时间'],
      columnValues: ['文件名称', '文件类型', '文件访问路径', '创建人', '创建时间', '修改人', '修改时间'],
      columns: ['文件名称', '文件类型', '文件访问路径', '创建人', '创建时间', '修改人', '修改时间'],
      checkAll: true,
      isIndeterminate: true,
      showPopover: false,
      drawer: false,
      direction: "rtl",
      uploadUrl: "http://localhost:9090/file/insert"
    }
  },
  methods: {
    beforeUpload(file) {
      // 创建 FormData 对象，并添加文件参数
      const formData = new FormData()
      formData.append('multipartFile', file)
      // 发送文件上传请求
      this.axios.post(this.uploadUrl, formData, {headers: {"token": localStorage.getItem("token")}})
          .then(reponse => {
            if (reponse.data.statusCode == 200) {
              this.$message.success('文件上传成功！')
            } else {
              this.$message.error('文件上传失败！')
            }
          })
      this.$refs.uploadRef.fileList.push(file)
      // 必须返回 false，否则 el-upload 组件会默认将文件上传到临时文件夹
      return false
    },
    uploadFile() {
      this.drawer = true;
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            this.selectQueryList({page: this.currentPage, pageSize: this.pageSize});
            done();
          })
          .catch(_ => {
          });
    },
    deleteRow(index, row) {
      this.$confirm('此操作将删除此条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteFile(row.id)
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '已取消删除此条数据'
        });
      });
    },

    updown(index, row) {
      this.updownFile(row.id);
    },
    handleCheckAllChange(val) {
      this.columnValues = val ? this.columns : [];
      this.isIndeterminate = false;
    }, handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.columns.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.columns.length;
    },
    submitFormShowCol(formName) {
      this.showCol = this.columnValues;
      this.showPopover = false;
      this.loading = true;
      setTimeout(() => {
        this.loading = false;
      }, 1000);
    },
    resetFormShowCol(formName) {
      this.columnValues = ['文件名称', '文件路径', '创建人', '创建时间', '修改人', '修改时间']
      this.showCol = this.columnValues;
      this.showPopover = false;
      this.loading = true;
      setTimeout(() => {
        this.loading = false;
      }, 1000);
    },
    handleHide() {
      this.columnValues = this.showCol;
    },
    onSubmit(formName) {
      let data = {
        fileName: this.selectFile.fileName,
        createDateStart: this.selectFile.createDate == null || this.selectFile.createDate.length == 0 ? null : this.formatDate(this.selectFile.createDate[0]),
        createDateEnd: this.selectFile.createDate == null || this.selectFile.createDate.length == 0 ? null : this.formatDate(this.selectFile.createDate[1]),
        page: this.currentPage,
        pageSize: this.pageSize
      }
      this.selectQueryList(data);
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.selectFile.createDate = [];
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    formatDate(dateString) {
      let date = new Date(dateString);

      let year = date.getFullYear();
      let month = ("0" + (date.getMonth() + 1)).slice(-2);
      let day = ("0" + date.getDate()).slice(-2);

      let hours = ("0" + date.getHours()).slice(-2);
      let minutes = ("0" + date.getMinutes()).slice(-2);
      let seconds = ("0" + date.getSeconds()).slice(-2);

      let formattedDateTime = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;

      return formattedDateTime;
    },
    updownFile(id) {
      let url = "http://114.55.111.65:9090/file/downLoad/" + id;
      console.log(id)
      //let token = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySW5mbyI6IntcInVzZXJJZFwiOjF9IiwiZXhwIjoxNjk0MTU2NzY5fQ.2l7X0-E8twF3EJt9Ek1bVFv0T7rq0UJCw8oLCZFKZV0";
      this.axios({
        method: "post",
        url: url,
        responseType: "blob", withCredentials: false, // 表明返回服务器返回的数据类型
        headers: {
          'token': localStorage.getItem("token")
        }
      }).then((res) => {
        // 处理返回的文件流
        if (res.status == 200) {
          let blob = new Blob([res.data], {type: res.data.type});
          //获取fileName,截取content-disposition的filename；按=分割，取最后一个
          const fileName = decodeURI(res.headers['content-disposition'].split("=")[1], "UTF-8");
          let downloadElement = document.createElement("a");
          let href = window.URL.createObjectURL(blob); //创建下载的链接
          downloadElement.href = href;
          downloadElement.download = fileName; //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href); //释放blob
          this.$message.success("文件下载成功!");
        } else {
          this.$message.error(res.message);
        }
      }).catch(error => {
        console.log(error)
        this.$notify.error({
          title: '错误',
          message: error.message
        });
      });
    },
    deleteFile(id) {
      let url = "http://114.55.111.65:9090/file/delete/" + id;
      //let token = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySW5mbyI6IntcInVzZXJJZFwiOjF9IiwiZXhwIjoxNjk0MTU2NzY5fQ.2l7X0-E8twF3EJt9Ek1bVFv0T7rq0UJCw8oLCZFKZV0";
      this.axios.post(url, null, {
        headers: {
          'token': localStorage.getItem("token")
        }
      }).then(reponse => {
        let code = reponse.data.statusCode;
        if (code == "200") {
          this.$message.success("删除成功!");
          this.selectQueryList({page: this.currentPage, pageSize: this.pageSize});
        } else {
          this.$notify.error({
            title: '错误',
            message: reponse.data.message
          });
        }
      }).catch(error => {
        console.log(error)
        this.$notify.error({
          title: '错误',
          message: error.message
        });
      });
    },
    selectQueryList(selectType) {
      let url = "http://114.55.111.65:9090/file/query-page";
      //let token = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySW5mbyI6IntcInVzZXJJZFwiOjF9IiwiZXhwIjoxNjk0MTU2NzY5fQ.2l7X0-E8twF3EJt9Ek1bVFv0T7rq0UJCw8oLCZFKZV0";
      this.loading = true;
      this.axios.post(url, selectType, {
        headers: {
          'token': localStorage.getItem("token")
        }
      }).then(reponse => {
        console.log(reponse)
        let code = reponse.data.statusCode;
        if (code == "200") {
          this.tableData = reponse.data.data.records;
          this.total = reponse.data.data.total;
        } else {
          this.$notify.error({
            title: '错误',
            message: reponse.data.message
          });
        }
      }).catch(error => {
        console.log(error)
        this.$notify.error({
          title: '错误',
          message: error.message
        });
      });
      setTimeout(() => {
        this.loading = false;
      }, 1000);
    },
    getFileType(url) {
      const extension = url.split('.').pop().toLowerCase();
      switch (extension) {
        case 'jpg':
        case 'jpeg':
        case 'png':
        case 'gif':
          return '图片';
        case 'pdf':
          return 'PDF';
        case 'doc':
        case 'docx':
          return 'Word 文档';
        default:
          return '其他文件';
      }
    },
    getFileIconClass(url) {
      const extension = url.split('.').pop().toLowerCase();
      switch (extension) {
        case 'jpg':
        case 'jpeg':
        case 'png':
        case 'gif':
          return 'el-icon-picture-outline';
        case 'pdf':
          return 'el-icon-document';
        case 'doc':
        case 'docx':
          return 'el-icon-document';
        default:
          return 'el-icon-folder';
      }
    }
  },
  mounted() {
    this.selectQueryList({page: this.currentPage, pageSize: this.pageSize});
  }
}
</script>

<style>

</style>